<?php
namespace App\Logic\ZiNiao\Work\Download;

use App\Models\Basics\SysCountry;
use App\Models\File\FileOperation;
use App\Models\ZiNiao\TasksResults as TasksResultsModel;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
class Operation
{
    public static function exe()
    {
        $all = TasksResultsModel::query()
            ->whereIn('rpaId',['1271','1655272611','1655272729','1655272808','1655272942'])
            ->where('status',0)
            ->get();
        $n = 0;
        $arr = ['1271'=>2,'1655272611' => 1,'1655272729' => 5,'1655272808' => 3,'1655272942' => 4];
        foreach($all as $_all) {
            $fileDir = FileOperation::fileDir(substr($_all->reportFromDate, 0, 10));
            $country_id = SysCountry::getIdByCountry($_all->siteCode);
            $fileName = FileOperation::fileName($country_id, $arr[$_all->rpaId], 1, $_all->fileName);
            $saveFilePath = public_uploads_path($fileDir) . DIRECTORY_SEPARATOR . $fileName;
            $fileDir = dirname($saveFilePath);
            if (!is_dir($fileDir)) {
                mkdir($fileDir, 0777, true);
            }
            $n++;
            echo '---start---：' . $n . '=============' . PHP_EOL;
            try {
                $client = new Client();
                $resource = fopen($saveFilePath, 'w');
                $client->request('GET', $_all->downloadUrl, ['sink' => $resource]);
                $fs = FileOperation::query()->firstOrNew([
                    'file_date' => msectimeFormat($_all->reportFromDate),
                    'country_id' => $country_id,
                    'file_type' => $arr[$_all->rpaId],
                    'file_name' => $_all->fileName,
                    'user_id' => 1,
                ]);
                $fs->save();
                $_all->status = 1;
                $_all->save();
            } catch (GuzzleException $ge) {
                var_dump($ge->getMessage());
            } catch (\Exception $e) {
                var_dump($e->getMessage());
            }
        }
    }
}
